package com.navcoo.yidaaddproapi.config;

import cn.hutool.json.JSONUtil;
import com.navcoo.yidaaddproapi.response.Result;
import com.navcoo.yidaaddproapi.response.exception.ResultStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;


/**
 * 接口拦截器
 *
 * @author WY
 * @date 2024/01/26
 */
@Slf4j
@Component
public class MyInterfaceInterceptor implements HandlerInterceptor {

    @Value("${api.token}")
    String apiToken;

    /**
     * 前处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestToken = request.getHeader("api-token");
        log.info("请求api-token：" + requestToken);
        if (apiToken.equals(requestToken)) {
            log.info("api-token验证成功");
            return true;
        } else {
            log.info("api-token验证失败");
            PrintWriter writer = null;
            try {
                Result<Object> failure = Result.failure(ResultStatus.UNAUTHORIZED);
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Type", "application/json");
                writer = response.getWriter();
                writer.write(JSONUtil.toJsonStr(failure));
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
            return false;
        }
    }

    /**
     * 处理后
     *
     * @param request      请求
     * @param response     响应
     * @param handler      处理程序
     * @param modelAndView 模型和视图
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 完成后
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
